package model.dao;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import model.entity.Photo;
import model.entity.User;

@Stateless
@Local(UserDaoLocal.class)
public class UserDaoBean extends GenericDaoBean<User, Integer> implements
		UserDaoLocal {

	@Override
	public User findMailPassword(String email, String password) {
		try{
			Query q = em
					.createNamedQuery("findMailPassword");
			q.setParameter("mail", email);
			q.setParameter("password", password);
			return (User) q.getSingleResult();
		}catch(NoResultException e){
			return null;
		}
	}

	@Override
	public boolean mailExists(String email) {
		try{
			Query q = em.createQuery("SELECT u FROM User u WHERE u.email=:mail");
			q.setParameter("mail", email);
			if(q.getSingleResult()!=null){
				return true;
			}
			return false;
		}catch(NoResultException e){
			return false;
		}
	}

	@Override
	public List<User> searchByName(String name) {
		try{
			Query q = em
					.createQuery("SELECT u FROM User u WHERE u.firstName LIKE :name OR " +
							"u.lastName LIKE :name");
			q.setParameter("name", "%"+name+"%");
			return q.getResultList();
		}catch(NoResultException e){
			return null;
		}
	}

	@Override
	public int removeFollower(Integer following, Integer follower) {
		try{
			Query q = em.createNativeQuery("DELETE FROM follows WHERE following_id=? AND follower_id=?");
			q.setParameter(1, following);
			q.setParameter(2, follower);
			return  q.executeUpdate();
		}catch(NoResultException e){
			return -1;
		}
	}

}
